const util=require('util')
const {User}=require('../models/user')
const {generateToken}=require('../../core/util')
const {Auth}=require('../../middlewares/auth')
const axios=require('axios')

class WXManager{
	
	static async codeToToken(code){
		//email password
		//code 小程序生成
		//code appid appsecret
		const url = util.format(global.config.wx.loginUrl,
			global.config.wx.appID,global.config.wx.appSecret,code)
		
		const result=await axios.get(url)
		if(result.status!==200){
			throw new global.errs.AuthFailed('openid获取失败')
		}
		const errcode=result.data.errcode
		const errmsg=result.data.errmsg
		// console.log('===========')
		// console.log(result.data)
		if(errcode){
			throw new global.errs.AuthFailed('openid获取失败:'+errmsg)
		}
		//openid
		//档案
		let user=await User.getUserByOpenid(result.data.openid)
		if(!user){
			await User.registerByOpenid(result.data.openid)
		}
		return generateToken(user.id,Auth.USER)
	}
}

module.exports={
	WXManager
}